import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { Image, Input } from "@nutui/nutui-react-taro";
import { useContext } from "react";
import { LoginContext } from "@/context/login-provider";
import { UserContext } from "@/context/user-provider";
import { userUpdate } from "@/api/login";
import { baseUrls } from "@/utils/request";
import { useState } from "react";

const Member = () => {
  const { member, getUser } = useContext(UserContext);
  const { userInfo } = useContext(LoginContext);
  return (
    <View className="bg-[#F5F5F5] p-3 min-h-screen course-page">
      <View className="flex flex-col gap-2 items-center justify-center">
        <button
          open-type="chooseAvatar"
          onChooseAvatar={(e) => {
            Taro.uploadFile({
              url: baseUrls + "/app-api/infra/file/upload",
              filePath: e?.detail?.avatarUrl,
              name: "file",
              header: {
                "content-type": "multipart/form-data",
                token: userInfo?.accessToken,
                "tenant-id": 3,
              },
              success: (res) => {
                if (res.data) {
                  const resp = JSON.parse(res.data);
                  if (resp.code === 0) {
                    userUpdate({ ...member, avatar: resp.data }).then(() => {
                      getUser();
                    });
                  } else {
                    Taro.showToast({
                      icon: "none",
                      title: resp.msg,
                    });
                  }
                }
              },
              fail: (_) => {
                Taro.showToast({
                  icon: "none",
                  title: "头像上传失败，请重试",
                });
              },
            });
          }}
          onClick={(e) => {
            e.stopPropagation();
          }}
          className="w-[100px] h-[100px] !p-0 rounded-full overflow-hidden"
        >
          <Image width={110} height={110} src={member?.avatar} />
        </button>
        <View className="text-xs font-semibold">点击设置头像</View>
      </View>
      <View className="mt-4 flex items-center gap-2 text-sm bg-white pl-4">
        <Text>昵称:</Text>
        <Input
          placeholder="请输入昵称"
          defaultValue={member?.nickname}
          onBlur={(nickname) => {
            userUpdate({ ...member, nickname }).then(() => {
              getUser();
              Taro.showToast({
                icon: "none",
                title: "修改成功",
              });
            });
          }}
        />
      </View>
    </View>
  );
};

export default Member;
